﻿using System.Collections.Generic;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class CacheTokenDictionary: ICacheTokenDictionary
    {
        private readonly object _lock = new object();
        public CacheTokenDictionary()
        {
            _tokenDictionary = new Dictionary<int, CacheTokenEntity>();
        }
        private Dictionary<int,CacheTokenEntity> _tokenDictionary;
        /// <summary>
        /// add token in dictionary
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="token"></param>
        /// <param name="minute"></param>
        public void AddToken(int UserId, string token, int minute = 30)
        {
            string MD5token = MD5Encrypt.Encrypt(token);
            if (_tokenDictionary.ContainsKey(UserId))
            {
                _tokenDictionary[UserId].SetToken(MD5token,minute);
                return;
            }
            
            CacheTokenEntity tokenEntity = new CacheTokenEntity(MD5token,minute);
            _tokenDictionary.Add(UserId, tokenEntity);
        }

        /// <summary>
        /// true-有效
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool AnyToken(int UserId, string token)
        {
            string MD5token = MD5Encrypt.Encrypt(token);
            if (_tokenDictionary.ContainsKey(UserId))
            {
                if (_tokenDictionary[UserId].GetToken() == MD5token)
                {
                    if (!_tokenDictionary[UserId].IsExpired())
                        return true;
                    else
                    {
                        return false;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// remove token
        /// </summary>
        /// <param name="UserId"></param>
        public void RemoveToken(int UserId)
        {
            if (_tokenDictionary.ContainsKey(UserId))
            {
                lock (_lock)
                {
                    _tokenDictionary.Remove(UserId);
                }
            }
        }
    }
}
